<template>
  <div>
    <el-card style="width: 50%">
      <el-form ref="formRef" :model="pwdForm" :rules="rules" label-width="80px" style="padding-right: 20px">

        <!--页面中不需要输入，会自动带出原始密码-->
        <el-form-item label="原始密码" prop="password">
          <el-input show-password v-model="pwdForm.password" placeholder="原始密码"></el-input>
        </el-form-item>

        <el-form-item label="新密码" prop="newPwd">
          <el-input show-password v-model="pwdForm.newPwd" placeholder="新密码"></el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="newPwd2">
          <el-input show-password v-model="pwdForm.newPwd2" placeholder="确认密码"></el-input>
        </el-form-item>

        <div style="text-align: center;margin-bottom: 20px">
          <el-button type="primary" @click="update">确认修改</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "Password",
  data(){

    //表单合理校验器
    const validatePwd = (rule,value,callback) => {
      console.log(this.pwdForm);
      if (value === '') {
        callback(new Error('请确认密码'))
      } else if (value !== this.pwdForm.newPwd){
        callback(new Error('两次输入的新密码不一致'))
      }else {
        callback()
      }
    }


    return {
      // user: JSON.parse(localStorage.getItem('userInfo') || '{}'),
      pwdForm: JSON.parse(localStorage.getItem('userInfo') || '{}'),
      rules: {
        'password': [
          { require: true,message: '请输入原始密码',trigger: 'blur'}
        ],
        'newPwd': [
          { require: true,message: '请输入新密码',trigger: 'blur'}
        ],
        'newPwd2': [
          { validator:validatePwd , require: true,trigger: 'blur'}
        ]
      }
    }
  },
  created(){
  },
  methods: {
    update(){
      //保存时表单校验
      this.$refs.formRef.validate((valid) => {

        if (valid){
          // this.user.password = this.user.newPwd
          //更新数据库和本地缓存数据
          // this.$request.put('/user/update',this.user).then(res => {
          this.$request.put('/user/resetPwd',this.pwdForm).then(res => {
            if (res.code === '200'){
              this.$message.success("保存成功")
              // //更新本地缓存信息
              // localStorage.setItem('userInfo',JSON.stringify(this.user))
              // //更新后新头像通过子传父的方式通信给manager外框架去更新
              // this.$emit('update:user',this.user)
              this.$router.push('/login')
            }else {
              this.$message.error("保存失败："+res.msg)
            }
          })
        }else {
          this.$message.error("表单校验未通过,请核对后再试")
        }
      })
    }
  }
}
</script>

<style scoped>
::v-deep(.el-form-item__label) {
  font-weight: bold;
}
</style>